package threaddemo11;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-08-06
 * Time: 22:44
 */
//同步方法与同步代码块解决数据安全问题
    //就是synchronized加在方法上
public class MyRunnable implements Runnable{
    private static int ticket=100;
    @Override
    public  void run() {
        while (true){
            //线程一执行
            if ("窗口一".equals(Thread.currentThread().getName())){
                //同步静态方法的锁对象是类型.class,同步方法的锁对象是this
                boolean result=synchronizedMethod();
                if(result){
                    break;
                }
            }
            //线程二执行
            if("窗口二".equals(Thread.currentThread().getName())){
                //同步代码块
                synchronized (MyRunnable.class){
                    //判断，如果票数小于等于0就停止售卖
                    if (ticket <= 0) {
                        break;
                    } else {
                        //正常的出票需要时间
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //售票后票数--
                        ticket--;
                        //打印窗口还剩多少张、
                        System.out.println(Thread.currentThread().getName() + "在卖票，还剩" + ticket + "张");
                    }
                }
            }
        }
    
    }
   private static synchronized   boolean  synchronizedMethod() {  //同步静态方法
    //  private  synchronized   boolean  synchronizedMethod() { //同步方法
        //判断，如果票数小于等于0就停止售卖
        if (ticket <= 0) {
            return true;
        } else {
            //正常的出票需要时间
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //售票后票数--
            ticket--;
            //打印窗口还剩多少张、
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩" + ticket + "张");
            return false;
        }
        
    }
    
}
